// 2025/11/12
// 合并k个升序链表

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode() : val(0), next(nullptr) {}
 *     ListNode(int x) : val(x), next(nullptr) {}
 *     ListNode(int x, ListNode *next) : val(x), next(next) {}
 * };
 */
class Solution {
    ListNode* mergeTwo(ListNode* l1, ListNode* l2)
    {
        ListNode head, *cur = &head;
        while(l1 && l2)
        {
            if(l1->val <= l2->val)
            {
                cur->next = l1;
                l1 = l1->next;
                cur = cur->next;
            }
            else
            {
                cur->next = l2;
                l2 = l2->next;
                cur = cur->next;
            }
        }
        if(l1)
            cur->next = l1;
        if(l2)
            cur->next = l2;
        return head.next;
    }
public:
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        if(lists.empty())
            return nullptr;
        int n = lists.size();
        while(n > 1)
        {
            int i = 0;
            for(i = 0; i * 2 + 1 < n; i++)
            {
                lists[i] = mergeTwo(lists[i * 2], lists[i * 2 + 1]);
            }
            if(i * 2 < n)
                lists[i++] = lists[n - 1];
            n = i;
        }
        return lists[0];
    }
};